import { createBrowserRouter, Navigate } from "react-router-dom";
import Main from "../pages/main";
import Home from "../pages/home";
import Mall from "../pages/mall";
import User from "../pages/user";
import PageOne from "../pages/other/pageOne";
import PageTwo from "../pages/other/pageTwo";
import Role from "../pages/system/role";
import Path from "../pages/system/path";
import Login from "../pages/login";
import menuConfig from "../config";

// 页面映射
const pageMap = {
  home: Home,
  mall: Mall,
  user: User,
  pageOne: PageOne,
  pageTwo: PageTwo,
  role: Role,
  path: Path,
};

// 动态生成 children 路由
const generateRoutes = (menus) => {
  return menus.map(item => {
    if (item.children) {
      return {
        path: item.path.replace(/^\//, ""),
        children: generateRoutes(item.children),
      };
    }
    return {
      path: item.path.replace(/^.*\//, ""),
      Component: pageMap[item.name],
    };
  });
};

const router = [
  {
    path: "/login",
    element: <Login />,
  },
  {
    path: "/",
    element: <Main />,
    children: [
      { path: "/", element: <Navigate to="/home" /> },
      ...generateRoutes(menuConfig),
    ],
  },
];

export default createBrowserRouter(router);